package com.atguigu.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.order.utils.HttpClient;
import com.atguigu.order.entity.TOrder;
import com.atguigu.order.entity.TPayLog;
import com.atguigu.order.mapper.TPayLogMapper;
import com.atguigu.order.service.TOrderService;
import com.atguigu.order.service.TPayLogService;
import com.atguigu.serviceBash.GlobalException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-07-16
 */
@Service
@Transactional(isolation = Isolation.SERIALIZABLE, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class TPayLogServiceImpl extends ServiceImpl<TPayLogMapper, TPayLog> implements TPayLogService {
    @Autowired
    TOrderService tOrderService;

    //生成支付二维码
    @Override
    public HashMap<String, String> createNative(String orderNo) {
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
//        查询订单号
        wrapper.eq("order_no", orderNo);
        TOrder tOrder = tOrderService.getOne(wrapper);
        wrapper = null;
//      1.设置生成二维码参数
        HashMap<String, String> params = Maps.newHashMap();
        params.put("appid", "wx74862e0dfcf69954");
        params.put("mch_id", "1558950191");
        params.put("nonce_str", WXPayUtil.generateNonceStr());
        params.put("body", tOrder.getCourseTitle());
        params.put("out_trade_no", tOrder.getOrderNo());
//      总金额  分为单位
        params.put("total_fee", tOrder.getTotalFee().multiply(new BigDecimal(100)).longValue() + "");
        params.put("spbill_create_ip", "127.0.0.1");
        params.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\\n");
        params.put("trade_type", "NATIVE ");
        HashMap<String, String> m = null;
//      2.发送请求
        HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
        try {
            client.setXmlParam(WXPayUtil.generateSignedXml(params, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();
//        3.默认返回XML格式数据
            String content = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(content);
            m = Maps.newHashMap();
            m.put("result_code", resultMap.get("result_code"));
            m.put("code_url", resultMap.get("code_url"));
//
            m.put("course_id", tOrder.getCourseId());
            m.put("course_title", tOrder.getCourseTitle());
            m.put("total_fee", tOrder.getTotalFee().toString());
            m.put("order_no", tOrder.getOrderNo());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return m;

    }

    // 查订单状态
    @Override
    public Map<String, String> getStatus(String orderNo) {
//
        Map m = Maps.newHashMap();
        m.put("appid", "wx74862e0dfcf69954");
        m.put("mch_id", "1558950191");
        m.put("out_trade_no", orderNo);
        m.put("nonce_str", WXPayUtil.generateNonceStr());
        try {
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");

            client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //6、转成Map
            //7、返回
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        //2、设置请求
        return Maps.newHashMap();
    }


    @Override
    public String payLogUpdate(Map<String, String> map) {
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", map.get("out_trade_no"));
        TOrder tOrder = tOrderService.getOne(wrapper);
        if (tOrder != null) {
            Integer integer = tOrder.getStatus();
//            已支付
            boolean b = integer.equals(1);
            if (b) {
                return "";
            } else {
                tOrder.setStatus(1);
                tOrderService.updateById(tOrder);
            }
        }


        try {
            TPayLog tPayLog = new TPayLog();
            tPayLog.setOrderNo(map.get("out_trade_no"));
            tPayLog.setPayTime(new Date());
            tPayLog.setTotalFee(new BigDecimal(map.get("total_fee")));
            tPayLog.setTransactionId(map.get("transaction_id"));
//           交易状态
            tPayLog.setTradeState(map.get("trade_state"));
//
            tPayLog.setPayType(1);
            tPayLog.setAttr(JSONObject.toJSONString(map));
//          添加记录完成
            int insert = baseMapper.insert(tPayLog);
            if (insert > 0) {
                return "OK";
            }
            throw new GlobalException("错误!", 20001);
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }


    }
}
